//
//  ViewController.m
//  JiangHu
//
//  Created by GT mac on 15/12/22.
//  Copyright © 2015年 GT mac. All rights reserved.
//

#import "ViewController.h"
#import <Reachability/Reachability.h>
#import <Masonry/Masonry.h>
#import <MBProgressHUD/MBProgressHUD.h>
#import "commonfile.h"
#import <WebViewJavascriptBridge/WebViewJavascriptBridge.h>
#import "WXApi.h"
#import <ASIHTTPRequest/ASIHTTPRequest.h>
#import <ASIDownloadCache.h>
#import <ASIWebPageRequest.h>
#import "JHURLCache.h"
//#import "JSONRepresentation.h"
#import "JSONKit.h"
#import <AlipaySDK/AlipaySDK.h>
#import "ScanQRcode.h"
//#import "WXApiManager.h"
//#import "WXApiRequestHandler.h"
//#import "Util/DataSigner.h"



@interface ViewController ()<WKNavigationDelegate,WKScriptMessageHandler, WKUIDelegate, UIWebViewDelegate, UIAlertViewDelegate, MBProgressHUDDelegate, UIPickerViewDataSource, UIPickerViewDelegate, UIPickerViewAccessibilityDelegate, ASIHTTPRequestDelegate,ASICacheDelegate>{
    JHURLCache *urlCache_;
}

@property (nonatomic, strong) MBProgressHUD *HUD;
@property (nonatomic, strong, readonly) JSContext *jsContext;
@property (nonatomic, strong) WKWebView *wkWebView;
@property (nonatomic, strong) UIWebView *uiWebView;
@property (nonatomic, strong) WKUserContentController *userContentController;
//@property (nonatomic, strong) WebViewJavascriptBridge *bridge;
@property (strong, nonatomic) JSContext *context;
@property (strong, nonatomic) NSURL *URL;
@property (strong, nonatomic) NSURLConnection *connection;
@property (strong, nonatomic) NSString *strTitle;
@property (strong, nonatomic) UIImageView *image;

- (void)checkIfWebButtonShouldShow;

@end

@implementation ViewController

//- (void)loadUrl : (NSURL *)url{
//    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:MAIN_URL];
//    [request setDelegate:self];
//    [request setDidFailSelector:@selector(webPageFetchFailed:)];
//    [request setDidFinishSelector:@selector(webPageFetchSuccessed:)];
//    
//    [request setDownloadCache:[ASIDownloadCache sharedCache]];
//    [request setCachePolicy:ASIAskServerIfModifiedWhenStaleCachePolicy|ASIAskServerIfModifiedCachePolicy];
//    [request setDownloadDestinationPath:[[ASIDownloadCache sharedCache] pathToStoreCachedResponseDataForRequest:request]];
//    [request startAsynchronous];
//}

+(instancetype)sharedManager{
    static dispatch_once_t onceToken;
    static ViewController *instance;
    dispatch_once(&onceToken,^{
        instance = [[ViewController alloc] init];
    });
    return instance;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES];
//    LocalSubstitutionCache *cache = [[LocalSubstitutionCache alloc] init];
//    [cache setMemoryCapacity:4*1024*1024];
//    [cache setDiskCapacity:10*1024*1024];
//    [NSURLCache setSharedURLCache:cache];

    if (self.uiWebView) {
        [self.uiWebView removeFromSuperview];
        self.uiWebView = nil;
    }else if (self.wkWebView){
        [self.wkWebView removeFromSuperview];
        self.wkWebView = nil;
    }else{
        [self initView];

        urlCache_ = [[JHURLCache alloc] initWithMemoryCapacity:1024 * 1024 diskCapacity:0 diskPath:nil];
        [NSURLCache setSharedURLCache:urlCache_];
        NSURL * url = [NSURL URLWithString:MAIN_URL];
        NSURLRequest * request = [NSURLRequest requestWithURL:url];
        if (IOS_8) {
            [self.uiWebView loadRequest:request];
        }else{
            [self.wkWebView loadRequest:request];
        }
//        NSString *path = [[[NSBundle mainBundle] bundlePath]  stringByAppendingPathComponent:MAIN_URL];
//        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
//        [self.webView loadRequest:request];
        
    
    }
}

- (void)reciveNotice: (NSNotification *)notification{
    NSLog(@"notification == %@",notification.object);
    [self.wkWebView evaluateJavaScript:[NSString stringWithFormat:@"ZJJH.qrCodeSuccess(\"%@\")",notification.object] completionHandler:nil];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}



//- (id)initWithURL:(NSURL *)pageURL{
//    if (self = [super init]) {
//        self.URL = pageURL;
//        LocalSubstitutionCache *urlCache = [[LocalSubstitutionCache alloc] initWithMemoryCapacity:20*1024*1024 diskCapacity:nil diskPath:nil];
//        [LocalSubstitutionCache setSharedURLCache:urlCache];
//    }
//    return self;
//}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if ([self.strTitle isEqualToString: @"取消支付"]) {
//        [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"ZJJH.wxOnPayRmbSuccess();"]];
    }
//    NSLog(@"webView location = '%@'", self.webView.request.URL.absoluteString);
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(reciveNotice:) name:@"QRCode" object:nil];
}


//- (void) webPageFetchFailed: (ASIHTTPRequest *)theRequest{
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"srror1.html" ofType:nil inDirectory:@"WebResources/Error"];
//    self.URL = [NSURL fileURLWithPath:path];
//    [self.webView loadRequest:[NSURLRequest requestWithURL:self.URL]];
//}
//
//- (void)webPageFetchSuccessed: (ASIHTTPRequest *)theRequest{
//    NSString *response = [NSString stringWithContentsOfFile:[theRequest downloadDestinationPath] encoding:[theRequest responseEncoding] error:nil];
//    [self.webView loadHTMLString:response baseURL:nil];
//}

- (void)btnReloadClicked{
    [self initView];
}

#pragma mark --微信分享
#pragma mark
- (void)wxShareMessagetitle:(NSString *)title desc: (NSString *)desc url: (NSString *)url mode: (NSString *)mode target: (NSString *)target{
    NSLog(@"title == %@",title);
    NSLog(@"desc == %@",desc);
    NSLog(@"url == %@",url);
    NSLog(@"mode == %@",mode);
    NSLog(@"target == %@",target);
    NSString *strPhoto = [NSString stringWithFormat:@"http://wx.buyubi.com/ZJJH_SHARE_ICON/share_icon_%@.jpg",mode];
    //    WXSceneSession  = 0,        /**< 聊天界面    */
    //    WXSceneTimeline = 1,        /**< 朋友圈      */
    //    WXSceneFavorite = 2,        /**< 收藏       */
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = title;
    message.description = desc;
    NSURL *urlPhoto = [NSURL URLWithString:[NSString stringWithFormat:@"%@",strPhoto]];
    UIImage *photo = [UIImage imageWithData:[NSData dataWithContentsOfURL:urlPhoto]];
    [message setThumbImage:photo];
    
    WXWebpageObject *webpageObject = [[WXWebpageObject alloc] init];
    webpageObject.webpageUrl = url;
    message.mediaObject = webpageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    if ([target isEqualToString:@"session"]) {
        req.scene = WXSceneSession;
    }else{
        req.scene = WXSceneTimeline;
    }
    
    [WXApi sendReq:req];

}


#pragma mark -- 微信图片分享
#pragma mark
- (void)WXSendImageData:(NSData *)imageData
              TagName:(NSString *)tagName
           MessageExt:(NSString *)messageExt
               Action:(NSString *)action
           ThumbImage:(UIImage *)thumbImage
              InScene:(enum WXScene)scene {
    WXImageObject *ext = [WXImageObject object];
    ext.imageData = imageData;
//    
//    WXMediaMessage *message = [WXMediaMessage messageWithTitle:nil
//                                                   Description:nil
//                                                        Object:ext
//                                                    MessageExt:messageExt
//                                                 MessageAction:action
//                                                    ThumbImage:thumbImage
//                                                      MediaTag:tagName];
//    
//    SendMessageToWXReq* req = [SendMessageToWXReq requestWithText:nil
//                                                   OrMediaMessage:message
//                                                            bText:NO
//                                                          InScene:scene];
    
//    [WXApi sendReq:req];
}

#pragma mark ---微信支付
#pragma mark
//String partnerId,String prepayId,String packageValue,String nonceStr,String timeStamp,String sign
- (void)WXPayRmbpartnerId :(NSString *)partnerId prepayId:(NSString *)prepayId packageValue:(NSString *)packageValue nonceStr: (NSString *)nonceStr timeStamp:(NSString *)timeStamp sign:(NSString *)sign{
    NSLog(@"partnerId == %@",partnerId);
    NSLog(@"prepayId == %@",prepayId);
    NSLog(@"package == %@",packageValue);
    NSLog(@"nonceStr == %@",nonceStr);
    NSLog(@"timeStamp == %@",timeStamp);
    NSLog(@"sign == %@",sign);
    PayReq *request = [[PayReq alloc] init];
    request.partnerId = partnerId;
    request.prepayId= prepayId;
    request.package = packageValue;
    request.nonceStr= nonceStr;
    request.timeStamp= [timeStamp intValue];
    request.sign= sign;
    [WXApi sendReq:request];
    
    
}

#pragma mark ---微信回调
-(void) onResp:(BaseResp*)resp
{
    NSLog(@"resp == %@",resp);
    //    NSString *strTitle;
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        NSString *strMsg = [NSString stringWithFormat:@"%d", resp.errCode];
        NSLog(@"strMsg == %d",resp.errCode);
        if ([strMsg isEqualToString:@"0"]) {
            [self.wkWebView evaluateJavaScript:[NSString stringWithFormat:@"ZJJH.wxOnShareSuccess(0)"] completionHandler:nil];
        }else{
            _strTitle = [NSString stringWithFormat:@"分享失败"];
        }
        [_strTitle addObserver:self
                    forKeyPath:@"wxShare"
                       options:NSKeyValueObservingOptionNew
                       context:nil];
    }else if ([resp isKindOfClass:[PayResp class]]){
        
        NSString *strPay = [NSString stringWithFormat:@"%d",resp.errCode];
        NSLog(@"strPay == %d",resp.errCode);
        if ([strPay isEqualToString:@"0"]) {
            [self.wkWebView evaluateJavaScript:[NSString stringWithFormat:@"ZJJH.wxOnPayRmbSuccess()"] completionHandler:nil];
        }else if ([strPay isEqualToString:@"-2"]) {
            _strTitle = [NSString stringWithFormat:@"取消支付"];
        }else{
            _strTitle = [NSString stringWithFormat:@"支付错误"];
        }
        [_strTitle addObserver:self
                    forKeyPath:@"wxPay"
                       options:NSKeyValueObservingOptionNew
                       context:nil];
    }
    //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:_strTitle message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    //    [alert show];
}

#pragma mark ---支付宝
- (void)alipayPay:(NSString *)data{
    NSLog(@"data == %@",data);
    
    [[AlipaySDK defaultService] payOrder:data fromScheme:URL_Schemes callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
        if ([[resultDic objectForKey:@"resultStatus"] intValue] == 9000) {
            [self.wkWebView evaluateJavaScript:[NSString stringWithFormat:@"ZJJH.aliOnPayRmbSuccess()"] completionHandler:nil];
        }
    }];
}

- (void) initView{
    BOOL isConnect = [self isConnectionAvailble];
    if (isConnect) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.automaticallyAdjustsScrollViewInsets = NO;
        
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        
        // 设置偏好设置
        config.preferences = [[WKPreferences alloc] init];
        // 默认为0
        config.preferences.minimumFontSize = 10;
        // 默认认为YES
        config.preferences.javaScriptEnabled = YES;
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
        
        // web内容处理池
        config.processPool = [[WKProcessPool alloc] init];
        
        // 通过JS与webview内容交互
        config.userContentController = [[WKUserContentController alloc] init];
        // 注入JS对象名称AppModel，当JS通过AppModel来调用时，
        // 我们可以在WKScriptMessageHandler代理中接收到
        [config.userContentController addScriptMessageHandler:self name:@"JHJSB"];
        
        self.wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, WIDTH, HEIGHT - 20)
                                            configuration:config];
        //            NSURL *path = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"];
        [self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:MAIN_URL]]];
        [self.view addSubview:self.wkWebView];
        
        // 导航代理
        self.wkWebView.navigationDelegate = self;
        // 与webview UI交互代理
        self.wkWebView.UIDelegate = self;
        
        // 添加KVO监听
        [self.wkWebView addObserver:self
                         forKeyPath:@"loading"
                            options:NSKeyValueObservingOptionNew
                            context:nil];
        [self.wkWebView addObserver:self
                         forKeyPath:@"title"
                            options:NSKeyValueObservingOptionNew
                            context:nil];
        [self.wkWebView addObserver:self
                         forKeyPath:@"estimatedProgress"
                            options:NSKeyValueObservingOptionNew
                            context:nil];
    }else{
        [self noNetWork];
    }
}

- (void) addUserScriptToUserContentController:(WKUserContentController *)userContentController{
    NSString *jumpShareContentsScriptString = [NSString stringWithContentsOfURL:MAIN_URL encoding:NSUTF8StringEncoding error:NULL];
    WKUserScript *userScript = [[WKUserScript alloc] initWithSource:self injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [userContentController addUserScript:userScript];
    [userContentController addScriptMessageHandler:self name:@"JHJSB"];
}

- (void)noNetWork{
    WS(ws);
    int padding = 150;
    UIView *ViewBackground = [[UIView alloc] init];
    ViewBackground.backgroundColor = bgColor;
    [self.view addSubview:ViewBackground];
    UIView *ViewBlock = [[UIView alloc] init];
    ViewBlock.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:ViewBlock];
    [ViewBackground mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.centerX.equalTo(ws.view);
        make.left.and.right.equalTo(ws.view);
        make.bottom.equalTo(ws.view).with.offset(-padding);
    }];
    [ViewBlock mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(ViewBackground.mas_bottom);
        make.bottom.equalTo(ws.view);
        make.left.and.right.equalTo(ws.view);
    }];
    
    UILabel *labTitle = [[UILabel alloc] init];
    labTitle.text = @"梦幻智驾 水浒江湖";
    labTitle.font = [UIFont systemFontOfSize:30];
    labTitle.textColor = [UIColor whiteColor];
    labTitle.textAlignment = NSTextAlignmentCenter;
    [ViewBackground addSubview:labTitle];
    [labTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(ws.view);
        make.top.equalTo(ws.view).with.offset(70);
    }];
    
    UIImageView *imgView = [[UIImageView alloc] init];
    imgView.image = [UIImage imageNamed:@"montain"];
    [ViewBackground addSubview:imgView];
    [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(ViewBackground.mas_bottom);
        make.centerX.equalTo(ws.view);
    }];
    
    UIImageView *imgNoNet = [[UIImageView alloc] init];
    imgNoNet.image = [UIImage imageNamed:@"noNet"];
    [ViewBackground addSubview:imgNoNet];
    [imgNoNet mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(ws.view).with.offset(-50);
        make.centerX.equalTo(ws.view);
    }];
    
    UILabel *labNoNet = [[UILabel alloc] init];
    labNoNet.text = @"无网络连接";
    labNoNet.textColor = [UIColor whiteColor];
    labNoNet.textAlignment = NSTextAlignmentCenter;
    labNoNet.font = [UIFont systemFontOfSize:15];
    [ViewBackground addSubview:labNoNet];
    [labNoNet mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(ws.view);
        make.top.equalTo(imgNoNet.mas_bottom).with.offset(10);
    }];
    
    UIButton *btnReload = [[UIButton alloc] init];
    [btnReload.layer setMasksToBounds:YES];
    [btnReload.layer setCornerRadius:5];
    btnReload.backgroundColor = buttonColor;
    [btnReload setTitle:@"刷新" forState:UIControlStateNormal];
    [btnReload setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [ViewBlock addSubview:btnReload];
    [btnReload mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(ViewBlock);
        make.size.mas_equalTo(CGSizeMake(155, 35));
    }];
    [btnReload addTarget:self action:@selector(btnReloadClicked) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark -- UIWebViewDelegate

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [self initView];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"Finish Load");
    self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.context .exceptionHandler = ^(JSContext *con, JSValue *exception) {
        NSLog(@"%@", exception);
        con.exception = exception;
    };
    self.context [@"JHJSB"] = self;
}

- (void)webViewDidStartLoad:(UIWebView *)webView{
//    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    self.HUD.delegate = self;
//    self.HUD.color = [UIColor lightGrayColor];
//    self.HUD.labelText = @"飞速加载中...";
//    [self.HUD hide:YES afterDelay:2];
}

-(BOOL)isConnectionAvailble{
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostName:main_url];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            NSLog(@"no network");
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            NSLog(@"WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            NSLog(@"WWAN");
            break;
    }
    return isExistenceNetwork;
}

- (void)telephone :(NSString *)phoneNumber{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:phoneNumber otherButtonTitles:nil, nil];
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSString *string=[NSString stringWithFormat:@"%@",[actionSheet buttonTitleAtIndex:buttonIndex]];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",string]]];
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if (!self.wkWebView.loading) {
//        NSLog(@"keyPath == &@\n object == %@\n change == %@\n context == %@\n",keyPath, obj)
//        NSString *js = @"wxShareMessage()";
//        [self.wkWebView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
//            NSLog(@"response: %@ error: %@", response, error);
//        }];
    }
}



- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [self.view reloadInputViews];
}


//页面开始加载时
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    NSLog(@"didStartProvisionalNavigation");
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    self.HUD.delegate = self;
//    self.HUD.color = [UIColor lightGrayColor];
//    self.HUD.labelText = @"飞速加载中...";
////    [self.HUD hide:YES afterDelay:2];
//    [self.HUD show:YES];
}

//内容开始返回时
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    NSLog(@"didCommitNavigation");
//    [self.HUD hide:YES];
//    NSString *strError = [NSString stringWithFormat:@"<html><center><font size=+5 color='black'>An error occurred:<br>%@</font></center></html>"];
//    [self.webView loadHTMLString:strError baseURL:nil];
//    [self initView];
}

//页面加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"didFailProvisionalNavigation");
}

//页面加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSLog(@"didFinishNavigation");
//    [self resetControl];
    if (webView.title.length > 0) {
        self.title = webView.title;
    }
}

#pragma mark - WKUIDelegate
- (void)webViewDidClose:(WKWebView *)webView {
//    NSLog(@"%s", __FUNCTION__);
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    NSLog(@"%s", __FUNCTION__);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert" message:@"JS调用alert" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
    NSLog(@"%@", message);
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {
//    NSLog(@"%s", __FUNCTION__);
    
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"confirm" message:@"JS调用confirm 1" preferredStyle:UIAlertControllerStyleAlert];
//    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        completionHandler(YES);
//    }]];
//    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        completionHandler(NO);
//    }]];
//    [self presentViewController:alert animated:YES completion:NULL];
    
//    NSLog(@"%@", message);
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
//    NSLog(@"%s", __FUNCTION__);
    
//    NSLog(@"%@", prompt);
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"textinput" message:@"JS调用输入框 1" preferredStyle:UIAlertControllerStyleAlert];
//    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
//        textField.textColor = [UIColor redColor];
//    }];
//    
//    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        completionHandler([[alert.textFields lastObject] text]);
//    }]];
//    
//    [self presentViewController:alert animated:YES completion:NULL];
}

#pragma mark -- WKScriptMessageHandler
//JS调用OC
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"JS调用OC");
    NSLog(@"%@", message.body);
    NSDictionary *dic = message.body;
    NSString *str = [dic objectForKey:@"body"];
    NSLog(@"str == %@",str);
    NSString *strFirst = [str substringWithRange:NSMakeRange(0, 1)];
    if ( [[dic objectForKey:@"body"] isEqualToString:@"QRCode"]) {
        ScanQRcode *qrCodeView = [[ScanQRcode alloc] init];
        [self presentViewController:qrCodeView animated:YES completion:nil];
    }else if (![strFirst isEqualToString:@"{"]) {
        if (str.length < 20) {
            [self telephone:str];
        }else{
            //支付宝
            [self alipayPay:str];
        }
    } else {
        NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *result = [jsonData objectFromJSONData];
        NSLog(@"result == %@",result);
        //微信
        //去{}
        NSString *str1 = [str stringByReplacingOccurrencesOfString:@"{" withString:@""];
        NSString *str2 = [str1 stringByReplacingOccurrencesOfString:@"}" withString:@""];
        //去""
        NSString *str3 = [str2 stringByReplacingOccurrencesOfString:@"\"" withString:@""];
        NSLog(@"str3 == %@",str3);
        //首字母
        NSString *firstChar = [str3 substringWithRange:NSMakeRange(0, 1)];
        if ([firstChar isEqualToString:@"s"]) {
            [self wxShareMessagetitle:[result objectForKey:@"shareTitle"] desc:[result objectForKey:@"desc"] url:[result objectForKey:@"shareAppMsgLink"] mode:[result objectForKey:@"mode"] target:[result objectForKey:@"target"]];
        }else{
            int lastLocation = 0;
            NSMutableArray *array = [[NSMutableArray alloc] init];
            for (int index = 0; index < 6; index ++) {
                NSRange range = [str3 rangeOfString:@","];
                NSLog(@"rang:%@",NSStringFromRange(range));
                NSString *str4 = [str3 substringWithRange:NSMakeRange(lastLocation, range.location)];
                NSLog(@"截取的值为：%@",str4);
                NSRange range2 = [str4 rangeOfString:@":"];
                NSLog(@"rang2:%@",NSStringFromRange(range2));
                NSString *str5 = [str4 substringWithRange:NSMakeRange(range2.location+1, range.location-range2.location-1)];
                [array addObject:str5];
                str3 = [str3 substringWithRange:NSMakeRange(range.location+1, str3.length-range.location-1)];
                NSLog(@"array22 == %@",array);
                NSLog(@"str3 == %@",str3);
            }
            NSLog(@"array == %@",array);
            NSString *strPackage = [NSString stringWithFormat:@"Sign=WXPay"];
            [array addObject:strPackage];
            [self WXPayRmbpartnerId:[array objectAtIndex:1] prepayId:[array objectAtIndex:2] packageValue:[array objectAtIndex:6] nonceStr:[array objectAtIndex:3] timeStamp:[array objectAtIndex:4]sign:[array objectAtIndex:5]];
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)sendLinkContent
{
    if (_delegate)
    {
        [_delegate RespLinkContent];
    }
}

@end
